/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Karthik T
 */
public final class message {
//TODO return only the packet and not whole array.. track length maybe? low prio
    public final static int MAX_PACKET_SIZE = 30;
    byte[] msg=new byte[MAX_PACKET_SIZE];
    public int pointer;
    char type;

    public message(char type) {
        msg[0] = (byte) type;
        pointer = 1;
        this.type = type;
    }
    public message(byte[]msg){
        System.arraycopy(msg, 0, this.msg,0,msg.length);
        type=(char) msg[0];
        pointer=1;
    }

    private static final byte[] intToByteArray(int value) {
        return new byte[] {
                (byte)(value >>> 24),
                (byte)(value >>> 16),
                (byte)(value >>> 8),
                (byte)value};
    }
    private static final int byteArrayToInt(byte [] b) {
        return (b[0] << 24)
            + ((b[1] & 0xFF) << 16)
            + ((b[2] & 0xFF) << 8)
            + (b[3] & 0xFF);
    }

    public void packInt(int val){
        byte[] num=new byte[4];
        num=intToByteArray(val);
        msg[pointer++]=num[0];
        msg[pointer++]=num[1];
        msg[pointer++]=num[2];
        msg[pointer++]=num[3];
    }

    public int unpackInt(){
        byte[] num=new byte[4];
        num[0]=msg[pointer++];
        num[1]=msg[pointer++];
        num[2]=msg[pointer++];
        num[3]=msg[pointer++];
        return(byteArrayToInt(num));
    }

    public byte[] getMsg() {
        return msg;
    }
}
